using System;
using System.Data;
using System.Web.Security;
using umbraco.BusinessLogic;
using umbraco.BasePages;
using umbraco.interfaces;
using Commerce.Common;
using SubSonic;

namespace CommerceForUmbraco.adminSection.tasks
{
    public class CategoryTasks : umbraco.interfaces.ITaskReturnUrl
    {
        private string _alias;
        private int _categoryId;
        private int _parentID;
        private int _typeID;
        private int _userID;

        public int UserId
        {
            set { _userID = value; }
        }

        public int TypeID
        {
            set { _typeID = value; }
            get { return _typeID; }
        }

        public int ParentID
        {
            set { _parentID = value; }
            get { return _parentID; }
        }

        public int CategoryId
        {
            set { _categoryId = value; }
            get { return _categoryId; }
        }

        public string Alias
        {
            get
            {
                return _alias;
            }
            set
            {
                _alias = value;
            }
        }

        public bool Save()
        {
            //Category thisCat = new Category();
            //thisCat.CategoryName = _alias;
            //thisCat.Save();

            int id = InsertCategory();
            m_returnUrl = string.Format("commerce/editCategory.aspx?c={0}", id);
            return true;
        }

        public bool Delete()
        {
            Category category = new Category(ParentID);

            try
            {
                int catChildrenCount = new SubSonic.Select(Category.Columns.ParentID).
                                            From(Category.Schema).Where(Category.Columns.ParentID).IsEqualTo(ParentID).GetRecordCount();

                if (catChildrenCount == 0)  // Only delete if no children
                {
                    new SubSonic.Destroy().From(Category.Schema).
                        Where(Category.Columns.CategoryID).IsEqualTo(category.CategoryID).Execute();
                }
                else
                {
                    return false;
                }
            }
            catch (Exception e)
            {
                umbraco.BusinessLogic.Log.Add(umbraco.BusinessLogic.LogTypes.Error, umbraco.BusinessLogic.User.GetUser(0), -1, String.Format("{0} -- {1}", e.Message, e.StackTrace));
            }

            m_returnUrl = string.Format("dashboard.aspx?app=commerce");
            return true;
        }

        public CategoryTasks()
        {

        }

        #region ITaskReturnUrl Members
        private string m_returnUrl = "";
        public string ReturnUrl
        {
            get { return m_returnUrl; }
        }

        #endregion


        public int InsertCategory()
        {
            Category thisCat = new Category();
            thisCat.CategoryName = _alias;

            int nextCategoryID = 1;

            // check to see if we have records for this order already
            // SHIPPING
            int catExistsCount = new SubSonic.Query(Category.Schema).GetCount("categoryID");

            if (catExistsCount > 0)
            {

                int currMaxCatID = new SubSonic.Select(
                    SubSonic.Aggregate.Max(
                        Category.Columns.CategoryID, "MaxCategoryID")).
                    From(Category.Schema).ExecuteScalar<int>();

                nextCategoryID = currMaxCatID + 1;
            }

            SiteConfig.Load();

            int successOrNot = new SubSonic.Insert().Into(Category.Schema,
                        Category.Columns.CategoryID,
                        Category.Columns.CategoryName,
                        Category.Columns.CategoryGUID,
                        Category.Columns.CreatedOn,
                        Category.Columns.CreatedBy,
                        Category.Columns.ParentID,
                        Category.Columns.ModifiedOn,
                        Category.Columns.ModifiedBy,
                        Category.Columns.ShortDescription,
                        Category.Columns.LongDescription,
                        Category.Columns.ImageFile,
                        Category.Columns.ListOrder
                    ).Values(
                    nextCategoryID                       // CategoryID
                   , _alias                              // CategoryName
                   , System.Guid.NewGuid().ToString()    // CategoryGUID
                   , SubSonic.Utilities.Utility.FormatDate(DateTime.Now, true)   // CreatedOn
                   , "Commerce For Umbraco"              // CreatedBy
                   , 0                                   // ParentID
                   , SubSonic.Utilities.Utility.FormatDate(DateTime.Now, true)   // ModifiedOn
                   , "Commerce For Umbraco"              // ModifiedBy
                   , ""                                  // ShortDescription
                   , ""                                  // LongDescription
                   , DBNull.Value                        // ImageFile
                   , catExistsCount)                     // ListOrder
                    .Execute();

            if (successOrNot == 1)
            {
                thisCat = new Category("categoryName", _alias);
                //Category.AfterNewProduct(thisCat);
            }


            return thisCat.CategoryID;

        }

    }

    public class ProductTasks : umbraco.interfaces.ITaskReturnUrl
    {
        private string _alias;
        private int _parentID;
        private int _typeID;
        private int _userID;

        public int UserId
        {
            set { _userID = value; }
        }

        public int TypeID
        {
            set { _typeID = value; }
            get { return _typeID; }
        }

        public int ParentID
        {
            set { _parentID = value; }
            get { return _parentID; }
        }
	
        public string Alias
        {
            get
            {
                return _alias;
            }
            set
            {
                _alias = value;
            }
        }

        public bool Save()
        {
           int id = InsertProduct();
            m_returnUrl = string.Format("commerce/editProduct.aspx?p={0}", id);
            return true;
        }

        public bool Delete()
        {
            Product product = new Product(ParentID);

            Product.BeforeDeleteProduct(product);

            try
            {
                
                new SubSonic.Update(Product.Schema).Set(Product.Columns.IsDeleted).EqualTo(1)
                    .Where(Product.Columns.ProductID).IsEqualTo(product.ProductID).Execute();

                ProductCategoryMap.Delete("ProductID",product.ProductID);
            }
            catch (Exception e)
            {
                umbraco.BusinessLogic.Log.Add(umbraco.BusinessLogic.LogTypes.Error, umbraco.BusinessLogic.User.GetUser(0), -1, String.Format("{0} -- {1}", e.Message, e.StackTrace));
            }

            Product.AfterDeleteProduct(product);
            return true;
        }

        public ProductTasks()
        {

        }

        #region ITaskReturnUrl Members
        private string m_returnUrl = "";
        public string ReturnUrl
        {
            get { return m_returnUrl; }
        }

        #endregion

        public int InsertProduct()
        {
            Product product = new Product();
            int manufacturerId = 0;
            int.TryParse(TypeID.ToString(), out manufacturerId);

            int nextProductID = 1;

            int prodExistsCount = new SubSonic.Query(Product.Schema).GetCount("ProductID");

            if (prodExistsCount > 0)
            {
                int currMaxProdID = new SubSonic.Select(
                    SubSonic.Aggregate.Max(
                        Product.Columns.ProductID, "MaxProductID")).
                    From(Product.Schema).ExecuteScalar<int>(); 

                nextProductID = currMaxProdID + 1;
            }

            SiteConfig.Load();

            int successOrNot = new SubSonic.Insert().Into(Product.Schema,
                        Product.Columns.ProductID,            			
			            Product.Columns.Sku,
			            Product.Columns.ProductGUID,
			            Product.Columns.ProductName,
			            Product.Columns.ShortDescription,
			            Product.Columns.ManufacturerID,
			            Product.Columns.AttributeXML,
			            Product.Columns.StatusID,
			            Product.Columns.ProductTypeID,
			            Product.Columns.ShippingTypeID,
			            Product.Columns.ShipEstimateID,
			            Product.Columns.TaxTypeID,
			            Product.Columns.StockLocation,
			            Product.Columns.OurPrice,
			            Product.Columns.RetailPrice,
			            Product.Columns.Weight,
			            Product.Columns.CurrencyCode,
			            Product.Columns.UnitOfMeasure,
			            Product.Columns.AdminComments,
			            Product.Columns.Length,
			            Product.Columns.Height,
			            Product.Columns.Width,
			            Product.Columns.DimensionUnit,
			            Product.Columns.IsDeleted,
			            Product.Columns.ListOrder,      			
			            Product.Columns.RatingSum,
			            Product.Columns.TotalRatingVotes,
			            Product.Columns.DefaultImage,
			            Product.Columns.CreatedOn,
			            Product.Columns.CreatedBy,
			            Product.Columns.ModifiedOn,
			            Product.Columns.ModifiedBy,          			
			            Product.Columns.Inventory
                    ).Values(
                    nextProductID                        // ProductID
                   , Alias                               // Sku
                   , System.Guid.NewGuid().ToString()    // ProductGUID
                   , Alias                               // ProductName
                   , Alias                               // ShortDescription
                   , manufacturerId                      // ManufacturerID
                   , DBNull.Value                        // AttributeXML
                   , 1                                   // StatusID
                   , 1                                   // ProductTypeID
                   , 1                                   // ShippingTypeID
                   , 1                                   // ShipEstimateID
                   , 1                                   // TaxTypeID
                   , DBNull.Value                        // StockLocation
                   , 0                                   // OurPrice
                   , 0                                   // RetailPrice
                   , 0                                   // Weight
                   , SiteConfig.CurrencyCode.ToString()  // CurrencyCode
                   , "each"                              // UnitOfMeasure
                   , DBNull.Value                        // AdminComments
                   , 0                                   // Length
                   , 0                                   // Height
                   , 0                                   // Width
                   , "each"                              // DimensionUnit
                   , 0                                   // IsDeleted
                   , 99                                  // ListOrder
                   , 4                                   // RatingSum
                   , 1                                   // TotalRatingVotes
                   , DBNull.Value                        // DefaultImage
                   , SubSonic.Utilities.Utility.FormatDate(DateTime.Now, true)   // CreatedOn
                   , "Commerce For Umbraco"              // CreatedBy
                   , SubSonic.Utilities.Utility.FormatDate(DateTime.Now, true)   // ModifiedOn
                   , "Commerce For Umbraco"              // ModifiedBy
                   , -1)                                 // Inventory
                    .Execute();

            if (successOrNot == 1)
            {
                product = new Product(Alias);
                Product.AfterNewProduct(product);
            }

            
            return product.ProductID;

        }
    }

    public class ManufacturerTasks : umbraco.interfaces.ITaskReturnUrl
    {
        private string _alias;
        private int _parentID;
        private int _typeID;
        private int _userID;

        public int UserId
        {
            set { _userID = value; }
        }

        public int TypeID
        {
            set { _typeID = value; }
            get { return _typeID; }
        }

        public int ParentID
        {
            set { _parentID = value; }
            get { return _parentID; }
        }

        public string Alias
        {
            get
            {
                return _alias;
            }
            set
            {
                _alias = value;
            }
        }

        public bool Save()
        {
            //Manufacturer thisManufacturer = new Manufacturer();
            //thisManufacturer.ManufacturerX = Alias;
            //thisManufacturer.Save();

            int id = InsertManufacturer();
            m_returnUrl = string.Format("commerce/editManufacturer.aspx?m={0}", id);

            return true;
        }

        public bool Delete()
        {

            return false;
        }

        public ManufacturerTasks()
        {

        }

        #region ITaskReturnUrl Members
        private string m_returnUrl = "";
        public string ReturnUrl
        {
            get { return m_returnUrl; }
        }

        #endregion

        public int InsertManufacturer()
        {
            Manufacturer thisMfr = new Manufacturer();
            thisMfr.ManufacturerX = _alias;

            int nextManufacturerID = 1;

            // check to see if we have records for this order already
            // SHIPPING
            int mfrExistsCount = new SubSonic.Query(Manufacturer.Schema).GetCount("manufacturerID");

            if (mfrExistsCount > 0)
            {

                int currMaxMfrID = new SubSonic.Select(
                    SubSonic.Aggregate.Max(
                        Manufacturer.Columns.ManufacturerID, "MaxCategoryID")).
                    From(Manufacturer.Schema).ExecuteScalar<int>();

                nextManufacturerID = currMaxMfrID + 1;
            }

            SiteConfig.Load();

            int successOrNot = new SubSonic.Insert().Into(Manufacturer.Schema,
                        Manufacturer.Columns.ManufacturerID,
                        Manufacturer.Columns.ManufacturerX,
                        Manufacturer.Columns.CreatedOn,
                        Manufacturer.Columns.CreatedBy,
                        Manufacturer.Columns.ModifiedOn,
                        Manufacturer.Columns.ModifiedBy
                    ).Values(
                    nextManufacturerID                   // ManufacturerID
                   , _alias                              // Manufacturer
                   , SubSonic.Utilities.Utility.FormatDate(DateTime.Now, true)   // CreatedOn
                   , "Commerce For Umbraco"              // CreatedBy
                   , SubSonic.Utilities.Utility.FormatDate(DateTime.Now, true)   // ModifiedOn
                   , "Commerce For Umbraco")             // ModifiedBy
                    .Execute();

            if (successOrNot == 1)
            {
                thisMfr = new Manufacturer("manufacturer", _alias);
                //Category.AfterNewProduct(thisCat);
            }


            return thisMfr.ManufacturerID;

        }
    }

    public class CouponTasks : umbraco.interfaces.ITaskReturnUrl
    {
        private string _alias;
        private int _parentID;
        private int _typeID;
        private int _userID;

        public int UserId
        {
            set { _userID = value; }
        }

        public int TypeID
        {
            set { _typeID = value; }
            get { return _typeID; }
        }

        public int ParentID
        {
            set { _parentID = value; }
            get { return _parentID; }
        }

        public string Alias
        {
            get
            {
                return _alias;
            }
            set
            {
                _alias = value;
            }
        }

        public bool Save()
        {
            object[] args = new object[2];
            args[0] = Alias;
            args[1] = Commerce.Promotions.CouponType.GetCouponType(TypeID);
            
            object tempcoup = Activator.CreateInstance(Commerce.Promotions.CouponType.GetCouponType(TypeID).CouponClassType, args);

            Commerce.Promotions.Coupon newCoupon = (Commerce.Promotions.Coupon)tempcoup;

           
            newCoupon.IsSingleUse = false;
            newCoupon.ExpirationDate = DateTime.UtcNow.AddYears(1);
            newCoupon.UserId = new Guid();
            newCoupon.SaveCoupon();
      

            m_returnUrl = string.Format("commerce/editCoupon.aspx?c={0}", Alias);

            return true;
        }

        public bool Delete()
        {
            try
            {
                Query q = new Query("CSK_Coupons");
                q.QueryType = QueryType.Delete;
                q.AddWhere("CouponCode", (string.IsNullOrEmpty(Alias) ? ParentID.ToString() : Alias));
                q.Execute();
            }
            catch (Exception e)
            {
                umbraco.BusinessLogic.Log.Add(umbraco.BusinessLogic.LogTypes.Error, umbraco.BusinessLogic.User.GetUser(0), -1, String.Format("{0} -- {1}", e.Message, e.StackTrace));
                return false;
            }

            return true;
        }

        public CouponTasks()
        {

        }

        #region ITaskReturnUrl Members
        private string m_returnUrl = "";
        public string ReturnUrl
        {
            get { return m_returnUrl; }
        }

        #endregion

    }

    public class ProductOptionsTasks : umbraco.interfaces.ITaskReturnUrl
    {
        private string _alias;
        private int _parentID;
        private int _typeID;
        private int _userID;

        public int UserId
        {
            set { _userID = value; }
        }

        public int TypeID
        {
            set { _typeID = value; }
            get { return _typeID; }
        }

        public int ParentID
        {
            set { _parentID = value; }
            get { return _parentID; }
        }

        public string Alias
        {
            get
            {
                return _alias;
            }
            set
            {
                _alias = value;
            }
        }

        public bool Save()
        {
            AttributeTemplate productOption = new AttributeTemplate();

            productOption.AttributeName = Alias;
            productOption.Description = "Set of " + Alias + " options.";
            productOption.AttributeTypeID = 1;

            productOption.Save();

            m_returnUrl = string.Format("commerce/editProductOptionTemplate.aspx?id={0}", productOption.TemplateID);

            return true;
        }

        public bool Delete()
        {
            return false;
        }

        public ProductOptionsTasks()
        {

        }

        #region ITaskReturnUrl Members
        private string m_returnUrl = "";
        public string ReturnUrl
        {
            get { return m_returnUrl; }
        }

        #endregion

    }
    public class ProductOptionTasks : umbraco.interfaces.ITaskReturnUrl
    {
        private string _alias;
        private int _parentID;
        private int _typeID;
        private int _userID;

        public int UserId
        {
            set { _userID = value; }
        }

        public int TypeID
        {
            set { _typeID = value; }
            get { return _typeID; }
        }

        public int ParentID
        {
            set { _parentID = value; }
            get { return _parentID; }
        }

        public string Alias
        {
            get
            {
                return _alias;
            }
            set
            {
                _alias = value;
            }
        }

        public bool Save()
        {
            AttributeItem productOptionItem = new AttributeItem();

            try
            {
                productOptionItem.TemplateId = ParentID;
                productOptionItem.Name = Alias;
                productOptionItem.Adjustment = 0;
                productOptionItem.SkuSuffix = "";
                productOptionItem.SortOrder = 0;

                productOptionItem.Save();

                m_returnUrl = string.Format("commerce/editProductOptionItem.aspx?id={0}", productOptionItem.AttributeItemId);

                return true;
            }
            catch (Exception e)
            {
                umbraco.BusinessLogic.Log.Add(umbraco.BusinessLogic.LogTypes.Error, umbraco.BusinessLogic.User.GetUser(0), -1, String.Format("{0} -- {1}", e.Message, e.StackTrace));

                return false;
            }
        }

        public bool Delete()
        {
            try
            {
                AttributeTemplate productOption = new AttributeTemplate(ParentID);

                Query q = new Query("CSK_Store_AttributeTemplate");
                q.QueryType = QueryType.Delete;
                q.AddWhere("TemplateID", productOption.TemplateID);
                q.Execute();

            }
            catch (Exception e)
            {
                umbraco.BusinessLogic.Log.Add(umbraco.BusinessLogic.LogTypes.Error, umbraco.BusinessLogic.User.GetUser(0), -1, String.Format("{0} -- {1}", e.Message, e.StackTrace));
                return false;
            }

            return true;
        }

        public ProductOptionTasks()
        {

        }

        #region ITaskReturnUrl Members
        private string m_returnUrl = "";
        public string ReturnUrl
        {
            get { return m_returnUrl; }
        }

        #endregion

    }
    public class ProductOptionItemTasks : umbraco.interfaces.ITaskReturnUrl
    {
        private string _alias;
        private int _parentID;
        private int _typeID;
        private int _userID;

        public int UserId
        {
            set { _userID = value; }
        }

        public int TypeID
        {
            set { _typeID = value; }
            get { return _typeID; }
        }

        public int ParentID
        {
            set { _parentID = value; }
            get { return _parentID; }
        }

        public string Alias
        {
            get
            {
                return _alias;
            }
            set
            {
                _alias = value;
            }
        }

        public bool Save()
        {
            return true;
        }

        public bool Delete()
        {
            try
            {
                AttributeItem productOptionItem = new AttributeItem(ParentID);
                
                Query q = new Query("CSK_Store_AttributeItem");
                q.QueryType = QueryType.Delete;
                q.AddWhere("AttributeItemId", productOptionItem.AttributeItemId);
                q.Execute();
               
            }
            catch (Exception e)
            {
                umbraco.BusinessLogic.Log.Add(umbraco.BusinessLogic.LogTypes.Error, umbraco.BusinessLogic.User.GetUser(0), -1, String.Format("{0} -- {1}", e.Message, e.StackTrace));
                return false;
            }

            return true;
        }

        public ProductOptionItemTasks()
        {

        }

        #region ITaskReturnUrl Members
        private string m_returnUrl = "";
        public string ReturnUrl
        {
            get { return m_returnUrl; }
        }

        #endregion

    } 

}
